<template>
  <div class="app">
    <!-- 第一行，销售数据展示 -->
    <el-card
      v-hasRole="['admin']"
      class="sale-show"
      shadow="always"
    >
      <p class="title">{{$t('statistics_sale_saledetails_402')}}</p>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-card
            shadow="hover"
            class="sale-show-container"
          >
            <animate-number
              :key="monthSaleData"
              from="1"
              :to="monthSaleData"
              class="saleData"
            /><br>
            <span>——</span>
            <h2>{{$t('statistics_sale_saledetails_403')}}</h2>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card
            shadow="hover"
            class="sale-show-container"
          >
            <animate-number
              :key="monthOrderData"
              from="1"
              :to="monthOrderData"
              class="saleData"
            /><br>
            <span>——</span>
            <h2>{{$t('statistics_sale_saledetails_404')}}</h2>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card
            shadow="hover"
            class="sale-show-container"
          >
            <animate-number
              :key="paySuccessData"
              from="1"
              :to="paySuccessData"
              class="saleData"
            /><br>
            <span>——</span>
            <h2>{{$t('statistics_sale_saledetails_405')}}</h2>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card
            shadow="hover"
            class="sale-show-container"
          >
            <animate-number
              :key="avgOrderData"
              from="1"
              :to="avgOrderData"
              class="saleData"
            /><br>
            <span>——</span>
            <h2>{{$t('statistics_sale_saledetails_406')}}</h2>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <!-- 第二行，展示某年每月销售额 -->
    <el-row :gutter="24">
      <el-col :span="12">
        <el-card
          v-hasRole="['admin']"
          class="sale-show"
          shadow="always"
          style="height: 450px"
        >
          <span class="title">{{$t('statistics_sale_saledetails_407', [ monthSaleFormattedyear ])}}</span>
          <el-date-picker
            v-model="monthSaleDate"
            type="year"
            :picker-options="{disabledDate}"
            @change="handleDateChange(monthSaleDate, 'monthSale')"
          />
          <div
            ref="monthSaleChart"
            class="details"
          />
        </el-card>
      </el-col>
      <!-- 第三行，展示某年每月订单量 -->
      <el-col :span="12">
        <el-card
          v-hasRole="['admin']"
          class="sale-show"
          shadow="always"
          style="height: 450px;margin-left:-10px;"
        >
          <span class="title">{{$t('statistics_sale_saledetails_408', [ monthOrderFormattedyear ])}}</span>
          <el-date-picker
            v-model="monthOrderDate"
            type="year"
            :picker-options="{disabledDate}"
            @change="handleDateChange(monthOrderDate, 'monthOrder')"
          />
          <div
            ref="monthOrderChart"
            class="details"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 第四行，展示各类别当月销售额 -->
    <el-card
      v-hasRole="['admin']"
      class="sale-show"
      shadow="always"
      style="height:750px"
    >
      <span class="title">{{$t('statistics_sale_saledetails_409', [ monthCategoryFormattedyear ])}}</span>
      <el-date-picker
        v-model="monthCategoryDate"
        type="year"
        :picker-options="{disabledDate}"
        @change="handleDateChange(monthCategoryDate, 'monthCategory')"
      /><br><br>
      <div
        ref="monthCategoryChart"
        class="categorydetails"
      />
    </el-card>
    <!-- 第五行，展示各产品当月销售额 -->
    <el-card
      v-hasRole="['admin','purchaser']"
      class="sale-show"
      shadow="always"
      style="width:auto;"
    >
      <span class="title">{{$t('statistics_sale_saledetails_410', [ monthProductFormattedyear ])}}</span>
      <el-date-picker
        v-model="monthProductDate"
        type="year"
        :picker-options="{disabledDate}"
        @change="handleDateChange(monthProductDate, 'monthProduct')"
      />&emsp;
      <el-button
        v-hasRole="['admin','purchaser']"
        type="success"
        @click="handleExport"
      >{{$t('statistics_sale_saledetails_411')}}</el-button>
      <br><br>
      <el-table
        :data="tableData"
        border
      >
        <el-table-column  
          type="index"  
          :label="$t('statistics_sale_saledetails_412')"  
          align="center"
          width="80"  
        />  
        <el-table-column  
          prop="productName"  
          :label="$t('statistics_sale_saledetails_413')"
          align="center"
        />
        <el-table-column
          :label="$t('statistics_sale_saledetails_414')"
          align="center"
          width="160px"
        >
          <template slot-scope="scope">
            <img
              v-if="scope.row.imageUrl != null"
              :src="scope.row.imageUrl"
              alt="Product Image"
              style="width: 120px; height: auto"
            >
            <span v-else>{{$t('statistics_sale_saledetails_415')}}</span>
          </template>
        </el-table-column>  
        <el-table-column  
          :label="$t('statistics_sale_saledetails_416')"
          align="center"
          width="150"
        >  
          <template slot-scope="scope">  
            <div
              v-for="(spec, index) in scope.row.speList"
              :key="index"
            >  
              {{ spec.color }} - {{ spec.size }}  
            </div>  
          </template>  
        </el-table-column>  
        <el-table-column  
          :label="$t('statistics_sale_saledetails_417')"
          width="150"
          align="center"
          icon="el-icon-d-caret"
        >
          <template slot="header">{{$t('statistics_sale_saledetails_418')}}<div
              style="float:right;margin-right:35px;margin-left:-25px;display: flex;flex-direction: column;align-items: center;"
            >
              <i
                id="asc"
                class="el-icon-caret-top"
                style="margin-bottom: -5px;color:#c0c4cc;cursor: pointer;"
                @click="handleSortChange('top')"
              /><i
                id="desc"
                class="el-icon-caret-bottom" 
                style="color:#c0c4cc;cursor: pointer;"
                @click="handleSortChange('bottom')"
              />
            </div>
          </template>
          <template slot-scope="scope">  
            <div
              v-for="(spec, index) in scope.row.speList"
              :key="index"
            >  
              {{ spec.saleVolume }}  
            </div>  
          </template>  
        </el-table-column>
        <el-table-column  
          prop="turnover"  
          :label="$t('statistics_sale_saledetails_419')"  
          sortable
          align="center"
          width="120"  
        />  
      </el-table>
    </el-card>
  </div>
</template>
<script>
import {
  getBasicSaleData,
  getCategorySaleData,
  getMonthlySaleData,
  getMonthlyOrderData,
  getAvaliableDate,
  getProductSaleDate
} from "@/api/dashboard";
import { exportProductTurnover } from "@/api/excel"
export default {
  name: "SaleDetails",
  data() {
    return {
      //可用日期
      availableYears:[],
      // 第一行，销售数据展示
      monthSaleData: 0, //本月营业额
      monthOrderData: 0, //本月订单量
      paySuccessData: 0, //支付成功率
      avgOrderData: 0, //平均订单交易额
      // 日期列表
      monthList: [
        this.$t('statistics_sale_saledetails_420'),
        this.$t('statistics_sale_saledetails_421'),
        this.$t('statistics_sale_saledetails_422'),
        this.$t('statistics_sale_saledetails_423'),
        this.$t('statistics_sale_saledetails_424'),
        this.$t('statistics_sale_saledetails_425'),
        this.$t('statistics_sale_saledetails_426'),
        this.$t('statistics_sale_saledetails_427'),
        this.$t('statistics_sale_saledetails_428'),
        this.$t('statistics_sale_saledetails_429'),
        this.$t('statistics_sale_saledetails_430'),
        this.$t('statistics_sale_saledetails_431'),
      ],
      
      // 第二行，月销售额展示
      monthlySalesTotal: [],
      // 第三行，月订单量展示
      monthlyOrderCount: [],

      // 时间选择器选择年份
      //月销售额
      monthSaleDate: new Date(),
      monthSaleFormattedyear: null,
      monthSaleFormattedmonth: null,
      //月订单量
      monthOrderDate: new Date(),
      monthOrderFormattedyear: null,
      //各类别当月销售额
      monthCategoryDate: new Date(),
      monthCategoryFormattedyear: null,
      //各产品当年销售额
      monthProductDate: new Date(),
      monthProductFormattedyear: null,

      //仪表盘变量
      // 月销售额
      monthSaleChart: null,
      monthSaleOption: null,
      // 月订单量
      monthOrderChart: null,
      monthOrderOption: null,
      // 类别销售额
      monthCategoryChart: null,
      monthCategoryOption: null,
      seriesConfig: null,
      //表格数据
      tableData: [], 
    };
  },
  created() {
    this.initDateFormats(this.monthSaleDate, "monthSale");
    this.initDateFormats(this.monthOrderDate, "monthOrder");
    this.initDateFormats(this.monthCategoryDate, "monthCategory");
    this.initDateFormats(this.monthProductDate, "monthProduct");
    // 获取可用日期
    getAvaliableDate().then((response) => {
      // console.log(111)
      this.availableYears=response.data
    });
      // 获取基础数据
      getBasicSaleData().then((response) => {
        // console.log(111)
        this.paySuccessData = response.data.payRate;
        this.monthSaleData = response.data.turnover;
        this.monthOrderData = response.data.saleCount;
        this.avgOrderData = response.data.aveTurnover;
      });
      // 获取当年月销售额数据
      getMonthlySaleData(this.monthSaleFormattedyear).then((response) => {
        this.monthlySalesTotal = response.data.data;
        this.initEcharts();
      });
      // 获取当年月订单量数据
      // console.log('getMonthlyOrderData')
      // console.log(this.monthOrderFormattedyear)
      getMonthlyOrderData(this.monthOrderFormattedyear).then((response) => {
        this.monthlyOrderCount = response.data.data;
        this.initEcharts();
      });
    // 获取当年产品销售额数据
    getProductSaleDate(this.monthProductFormattedyear,"ASC").then((response) => {
      this.tableData = response.data;
    });
  },
  beforeDestroy() {
    // if (this.rodNumber) {
    //   clearInterval(this.rodNumber); // 清除可能存在的定时器
    // }
  },
  mounted() {
    // this.initEcharts();
  },
  methods: {
    // 销售量升降序
    handleSortChange(iconType) {  
      var element1 = document.getElementById('asc');
      var element2 = document.getElementById('desc');
      // 升序
      if(iconType=='top'){
        element1.style.color = '#409eff';
        element2.style.color = '#c0c4cc';
        getProductSaleDate(this.monthProductFormattedyear,"ASC").then((response) => {
          this.tableData = response.data;
        });
      }
      // 降序
      if(iconType=='bottom'){
        element2.style.color = '#409eff';
        element1.style.color = '#c0c4cc';
        getProductSaleDate(this.monthProductFormattedyear,"DESC").then((response) => {
          this.tableData = response.data;
        });
      }
    },
    disabledDate(year) {
      // 如果日期不在可用日期列表中，则返回 true 以禁用该日期
      return !this.availableYears.includes(year.getFullYear());
    },
    handleDateChange(newValue, type) {
      if (newValue) {
        const year = newValue.getFullYear();
        if (type === "monthSale") {
          this.monthSaleFormattedyear = year;
          getMonthlyOrderData(this.monthSaleFormattedyear).then((response) => {
            this.monthlySalesTotal = response.data.data;
            this.monthSaleChart.setOption(
              {
                grid: {
                  left: "1%",
                  right: "0%",
                  bottom: "3%",
                  containLabel: true,
                },
                xAxis: {
                  data: this.monthList,
                },
                yAxis: {
                  type: "value",
                },
                series: [
                  {
                    data: this.monthlySalesTotal,
                    type: "bar",
                  },
                ],
              },
              true
            );
          });
        } 
        else if (type === "monthOrder") {
          this.monthOrderFormattedyear = year;
          getMonthlyOrderData(this.monthOrderFormattedyear).then((response) => {
            this.monthlyOrderCount = response.data.data;
            this.monthOrderChart.setOption(
              {
                xAxis: {
                  data: this.monthList,
                },
                yAxis: {
                  type: "value",
                },
                series: [
                  {
                    data: this.monthlyOrderCount,
                    type: "line",
                  },
                ],
              },
              true
            );
          });
        } 
        else if (type === "monthCategory") {
          this.monthCategoryFormattedyear = year; // 格式化year
          // 访问后端接口获取数据
          getCategorySaleData(year).then((response) => {
            if (response.data.length==0) {
              this.seriesConfig = {
                type: "bar",
                stack: "total",
                label: {
                  show: true,
                },
                emphasis: {
                  focus: "series",
                },
                data: [],
              };
            } else {
              this.seriesConfig = response.data.map((item) => ({
                name: item.name,
                type: "bar",
                stack: "total",
                label: {
                  show: true,
                },
                emphasis: {
                  focus: "series",
                },
                data: item.saleData,
              }));
            }
            this.monthCategoryChart.setOption(
              {
                series: this.seriesConfig,
                xAxis: {
                  type: "value",
                },
                yAxis: {
                  type: "category",
                  data: this.categoryMonthList,
                },
                grid: {
                left: "0%",
                right: "0%",
                bottom: "3%",
                containLabel: true,
                },
              },
              true
            );
          });
        } 
        else if (type === "monthProduct") {
          this.monthProductFormattedyear = year;
          getProductSaleDate(this.monthProductFormattedyear,"ASC").then((response) => {
          this.tableData = response.data;
        });
        }
      }
    },
    initDateFormats(date, type) {
      if (date) {
        const year = date.getFullYear();
        if (type === "monthSale") {
          this.monthSaleFormattedyear = year;
        } else if (type === "monthOrder") {
          this.monthOrderFormattedyear = year;
        } else if (type === "monthCategory") {
          this.monthCategoryFormattedyear = year;
        } else if (type === "monthProduct") {
          this.monthProductFormattedyear = year;
        }
      }
    },
    initEcharts() {
      // 月销售额
      this.monthSaleChart = this.$echarts.init(this.$refs.monthSaleChart);
      this.monthSaleChart.resize({
        width: 450,
        height: 350,
      });

      this.monthSaleOption = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "0%",
          right: "0%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: this.monthList,
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
          },
        ],
        series: [
          {
            name: this.$t('statistics_sale_saledetails_432'),
            type: "bar",
            barWidth: "90%",
            data: this.monthlySalesTotal,
          },
        ],
      };
      this.monthSaleOption &&
        this.monthSaleChart.setOption(this.monthSaleOption);

      // 月订单量
      this.monthOrderChart = this.$echarts.init(this.$refs.monthOrderChart);
      this.monthOrderChart.resize({
        width: 550,
        height: 390,
      });
      this.monthOrderOption = {
        tooltip: {
          trigger: "axis",
          backgroundColor: "rgba(0,0,0,.6)", // 设置窗口背景颜色
          borderColor: "rgba(147, 235, 248, .8)", // 设置窗口边框颜色
          textStyle: {
            color: "#FFF", // 设置窗口字体颜色
          },
        },
        xAxis: {
          type: "category",
          grid: {
            left: "0%",
            right: "0%",
            bottom: "0%",
            containLabel: true,
          },
          data: this.monthList,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: this.$t('statistics_sale_saledetails_433'),
            data: this.monthlyOrderCount,
            type: "line",
          },
        ],
      };
      this.monthOrderOption &&
        this.monthOrderChart.setOption(this.monthOrderOption);

      // 各类别月销售额
      this.monthCategoryChart = this.$echarts.init(
        this.$refs.monthCategoryChart
      );
      this.monthCategoryChart.resize({
        width: 1100,
        height: 630,
      });
      // 访问后端接口获取数据
      getCategorySaleData(this.monthCategoryFormattedyear).then((response) => {
        this.seriesConfig = response.data.map((item) => ({
          name: item.name,
          type: "bar",
          stack: "total",
          label: {
            show: true,
          },
          emphasis: {
            focus: "series",
          },
          data: item.saleData,
        }));
        this.monthCategoryOption = {
          series: this.seriesConfig, // 使用动态创建的 seriesConfig
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          legend: {},
          grid: {
            left: "0%",
            right: "0%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
          },
          yAxis: {
            type: "category",
            data: this.monthList,
          },
        };
        this.monthCategoryOption &&
          this.monthCategoryChart.setOption(this.monthCategoryOption);
      });
    },
    async handleExport(){
      await exportProductTurnover(this.monthProductFormattedyear).then((res) => {
          const a = document.createElement("a"); // 创建一个新的 a 标签
          const url = window.URL.createObjectURL(res); // 创建一个 URL 对象，表示 Blob 对象的内容
          a.href = url;// 将 a 标签的 href 设置为 URL 对象
          a.download = this.$t('statistics_sale_saledetails_434'); // 设置文件名
          document.body.appendChild(a);// 触发点击事件
          a.click();
          // 清理
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        })
        .catch((e) => {
          // console.log(e);
        });
    }
    
  },
};
</script>
<style lang="scss" scoped>
.title {
  margin-left: 20px;
  margin-right: 20px;
  margin-top: -10px;
  font-size: 25px;
  font-weight: bold;
  // font-size:large;
  color: rgb(86, 83, 83);
}
.sale-show,
.sale-show-container {
  height: 100%;
  margin: 10px;
  padding-top: 20px;
  padding-bottom: 20px;
}
.sale-show-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  height: 100%;
  margin: 10px;
  margin-top: 0px;
  padding-top: 0;
}
.sale-show-container h2 {
  text-align: center;
  margin: 0;
  font-weight: 150;
  color: rgb(177, 176, 176);
}
.saleData {
  font-size: 60px;
  font-weight: bold;
  color: rgb(47, 154, 248);
}
.details,
.categorydetails {
  width: 900px;
  height: 600px;
  margin: 0 auto;
}
.categorydetails {
  height: 800px;
}
</style>